<template>
    <div style="padding-left: 70px;">
        <div class="form-container">
            <el-form :inline="true" :model="formInline" class="demo-form-inline">
                <el-form-item label="站点名称">
                    <el-input v-model="formInline.stationname" placeholder="" clearable />
                </el-form-item>
                <el-form-item label="报警类型">
                    <el-select v-model="formInline.names" placeholder="报警类型" clearable style="width: 200px;">
                        <el-option label="爆管预警" value="1" />
                        <el-option label="压力过高" value="3" />
                        <el-option label="余氯低限" value="6" />
                        <el-option label="浊度超限" value="7" />
                        <el-option label="压力过低" value="4" />
                        <el-option label="余氯超限" value="5" />
                    </el-select>
                </el-form-item>
                <el-form-item label="报警时间">
                    <div class="block">
                        <el-date-picker v-model="value1" type="daterange" range-separator="至" start-placeholder=""
                            :disabled-date="disabledDate" end-placeholder="" :size="size" @calendar-change="changeTime"
                            @clear="clearValue()" />
                    </div>
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="formInline.state" placeholder="全部" clearable style="width: 200px;">
                        <el-option label="已处理" value="0" />
                        <el-option label="未处理" value="1" />
                        <!-- <el-option label="全部" value="" /> -->
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit">搜索</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="success" @click="chongzhi">重置</el-button>
                </el-form-item>

            </el-form>
        </div>
        <div>
            <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
                <el-tab-pane label="时间线" name="first">
                    <div class="timeline-container">
                        <el-timeline style="max-width: 100%">
                            <el-timeline-item v-for="item in paginatedLineList" :key="item.value" :timestamp="item.time"
                                placement="top" color="#e6a23c">
                                <el-card>
                                    <div class="alarmList">
                                        <div class="alarmList1">
                                            <div class="alarmList1_item">{{ item.information }}</div>
                                            <div class="alarmList1_item">
                                                <el-button type="success" size="small"
                                                    v-if="item.isactive === '0'">已处理</el-button>
                                                <el-button type="danger" size="small" v-else>未处理</el-button>
                                            </div>
                                        </div>

                                        <div class="alarmList_item">
                                            <div class="alarmList_item1">报警时间: {{ item.starttime }}</div>
                                            <div class="alarmList_item1">站点名称: {{ item.stationname }}</div>
                                        </div>
                                        <div class="alarmList_item">
                                            <div class="alarmList_item1" v-if="item.isactive === '0'">状态:已处理</div>
                                            <div class="alarmList_item1" v-else>状态:未处理</div>
                                            <div class="alarmList_item1">报警值:{{ item.value }}</div>
                                        </div>
                                    </div>
                                </el-card>
                            </el-timeline-item>
                        </el-timeline>
                        <el-empty description="暂无数据" v-if="paginatedLineList.length == 0" />
                    </div>
                    <div class="demo-pagination-block">
                        <el-pagination v-model:current-page="currentPage" :page-size="pageSize"
                            layout="total, sizes, prev, pager, next, jumper" :total="totalItems"
                            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                    </div>
                </el-tab-pane>
                <el-tab-pane label="热力图" name="second">
                    <div style="height: 100%;width: 100%;">
                        <offciaHeatmap class="timeline-container1"></offciaHeatmap>
                    </div>
                </el-tab-pane>
            </el-tabs>
        </div>
    </div>

</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { reactive } from 'vue'
import offciaHeatmap from '../../components/DyEcharts/offciaHeatmap.vue' //管线长度（柱状图）
import { AlarmRecord, DyWarningStabyHour } from '../../http/http'
import bus from '../../tools/eventBus'
const activeName = ref('first')
const currentPage = ref(1);
const pageSize = ref(10);
const startTime = ref(null);
const endTime = ref(null);
const tableName = ref('时间线');
const lineList = ref([]);
const heatmapList = ref([]);
const dateRange = ref([]);
// 默认展示当天日期的开始和结束时间
const today = new Date();
const startDate = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0); // 今天的开始时间 00:00:00
const endDate = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59, 999); // 今天的结束时间 23:59:59.999

const value1 = ref([startDate, endDate]);
const TimeValue = value1.value.map(timeString => {
    const date = new Date(timeString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，+1调整为1-12
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`; // 格式化为 YYYY-MM-DD
})

dateRange.value = TimeValue

console.log(TimeValue, 'TimeValue');
startTime.value = TimeValue[0]
endTime.value = TimeValue[1]


const formInline = reactive({
    user: '',
    region: '',
    code: '',
    type: '',
    name: '',
    name1: '',
    names: '3',
    state: "",
    date: new Date(),
    stationname: ''
})

function handleClick(e) {
    console.log(e.props.label, '热力图');
    tableName.value = e.props.label
    if (e.props.label === '时间线') {
        onSubmit()
    }
}

//清空时间
function clearValue() {
    console.log('11');
    startTime.value = ''
    endTime.value = ''
}
function generateDateRange(start, end) {
    const startDate = new Date(start);
    const endDate = new Date(end);
    const dates = [];

    // 逐天生成日期
    let currentDate = new Date(startDate);
    while (currentDate <= endDate) {
        const year = currentDate.getFullYear();
        const month = String(currentDate.getMonth() + 1).padStart(2, '0'); // 月份从0开始，+1调整为1-12
        const day = String(currentDate.getDate()).padStart(2, '0');

        dates.push(`${year}/${month}/${day}`);

        // 增加一天
        currentDate.setDate(currentDate.getDate() + 1);
    }

    return dates;
}
// 判断禁用日期的逻辑
const disabledDate = (time) => {
    return time.getTime() > Date.now() // 禁用今天之后的所有日期
}
function changeTime(e) {
    console.log(e[0], e[1], 'e');
    // 获取起始和结束日期
    const startDate = e[0];
    const endDate = e[1];
    console.log(startDate, endDate);

    // 生成日期范围并格式化
    dateRange.value = generateDateRange(startDate, endDate);
    // bus.emit('Heatmap', {
    //     HeatmapTime: dateRange.value,
    //     // HeatmapList:
    // })


    // 转换为本地时间
    const localTimes = e.map(timeString => {
        const date = new Date(timeString);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，+1调整为1-12
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`; // 格式化为 YYYY-MM-DD
    });

    // console.log(localTimes);
    startTime.value = localTimes[0]
    endTime.value = localTimes[1]
}


function dialogData() {
    return {
        "startTime": startTime.value,
        "endTime": endTime.value,
        "warnType": formInline.names,
        "isActive": formInline.state,
        "stationname": formInline.stationname
    }
}
function onSubmit() {
    HeatmapValueData()
    lineList.value = []
    if (tableName.value === '时间线') {
        // currentPage.value = '1'
        AlarmRecord(dialogData()).then((res) => {
            // console.log(res.data.returnValue.result);
            lineList.value = res.data.returnValue.result
            lineList.value.forEach(i => {
                i.value = Number(Number(i.value).toFixed(4));
                const valueNumber = i.information.slice(0, 2)
                switch (valueNumber) {// 添加单位字段
                    case '余氯':
                        i.value = ensureUnit(i.value, 'mg/L')
                        break;
                    case '浊度':
                        i.value = ensureUnit(i.value, 'NTU')
                        break;
                    case '压力':
                        i.value = ensureUnit(i.value, 'Mpa')
                    case '爆管':
                        i.value = ensureUnit(i.value, 'Mpa')
                        break;
                }

            })
        })
    } else {
        // HeatmapValueData()
        // onSubmit()
    }

}
//热力图数值

function HeatmapValueData() {
    DyWarningStabyHour(dialogData()).then((res) => {
        // changeTime()
        const a = res.data.returnValue.result
        const b = [res.data.returnValue.result.length - 1]
        if (startTime.value === '' && endTime.value === '' && !formInline.names) {
            dateRange.value = generateDateRange(a[0]["starttime"].split(" ")[0], a[b]["starttime"].split(" ")[0])
        } else if (startTime.value === '' && endTime.value === '' && formInline.names) {
            dateRange.value = generateDateRange(a[0]["starttime"].split(" ")[0], a[b]["starttime"].split(" ")[0])
        }
        console.log(res.data.returnValue.result, dateRange.value, '热力图数值');
        const dateIndexMap = dateRange.value.reduce((acc, date, index) => {
            const formattedDate = date.replace(/\//g, '-'); // Format to match rawData
            acc[formattedDate] = index;
            return acc;
        }, {});
        // Step 2: Transform rawData by mapping date and time to respective indices
        const transformedData = res.data.returnValue.result.map(item => {
            const [date, hour] = item.starttime.split(' '); // Split date and hour
            const dateIndex = dateIndexMap[date];           // Lookup date index from map
            const hourIndex = parseInt(hour, 10);           // Convert hour to an integer
            const burstWarning = parseInt(item.burstwarning || item.highpressure || item.lowpressure || item.chlorinehigh || item.chlorinelow || item.turbidityhigh, 10); // Convert burstwarning to integer
            const burstWarning1 = parseInt(item.burstwarning, 10) + parseInt(item.highpressure, 10) + parseInt(item.lowpressure, 10) + parseInt(item.chlorinehigh, 10) + parseInt(item.chlorinelow, 10) + parseInt(item.turbidityhigh, 10);
            if (!formInline.names) {
                return [dateIndex, hourIndex, burstWarning1];    // Construct the result array

            } else {
                return [dateIndex, hourIndex, burstWarning];    // Construct the result array

            }
        });
        heatmapList.value = transformedData
        // 使用转换函数
        console.log(dateRange.value, 'dateRange.value');
        bus.emit('Heatmap', {
            HeatmapList: heatmapList.value,
            HeatmapTime: dateRange.value,
        })
    })
}

function ensureUnit(value, unit) {
    if (typeof value === 'number') {
        return `${value}${unit}`;
    } else if (typeof value === 'string') {
        // 检查是否已经包含单位
        if (!value.endsWith(unit)) {
            return `${value}${unit}`;
        }
        return value;
    }
    return value;  // 如果不是数字或字符串，直接返回原值
}
onMounted(() => {
    // 生成日期范围并格式化
    const dateRange = generateDateRange(startTime.value, endTime.value);

    // console.log(dateRange);
    // bus.emit('Heatmap', {
    //     HeatmapTime: dateRange,
    // })
    onSubmit()

})


const shortcuts = [
    {
        text: 'Last week',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            return [start, end]
        },
    },
    {
        text: 'Last month',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            return [start, end]
        },
    },
    {
        text: 'Last 3 months',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            return [start, end]
        },
    },
]

function chongzhi() {
    formInline.user = ''
    formInline.region = ''
    formInline.code = ''
    formInline.type = ''
    formInline.name = ''
    formInline.name1 = ''
    formInline.names = ''
    formInline.state = ''
    // 默认展示当天日期的开始和结束时间
    const today = new Date();
    const startDate = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0); // 今天的开始时间 00:00:00
    const endDate = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59, 999); // 今天的结束时间 23:59:59.999
    value1.value = [startDate, endDate],

        console.log(value1.value); // 输出: [今天的日期 00:00:00, 今天的日期 23:59:59.999]
    const TimeValue = value1.value.map(timeString => {
        const date = new Date(timeString);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，+1调整为1-12
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`; // 格式化为 YYYY-MM-DD
    })

    console.log(TimeValue, 'TimeValue');

}

// 计算后的时间线数据
const paginatedLineList = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value;
    const end = currentPage.value * pageSize.value;
    // console.log(paginatedLineList, 'paginatedLineList');
    return lineList.value.slice(start, end);
});


// 总条目数
const totalItems = computed(() => lineList.value.length);

// 处理页码变化
const handleCurrentChange = (page) => {
    currentPage.value = page;
};

// 处理每页条目数变化
const handleSizeChange = (size) => {
    pageSize.value = size;
    currentPage.value = 1; // 当每页条目数变化时，将页码重置为 1
};

</script>

<style>
.demo-form-inline {
    display: flex;
    justify-content: center;
}

.form-container {
    margin-top: 10px;
}

.alarmList {
    width: 100%;
    display: flex;
    justify-content: flex-start;
    font-size: 18px;
}

.alarmList_item {
    width: 350px;
    margin-left: 50px;
}

.alarmList_item1 {
    width: 350px;
    padding: 10px;
}

.alarmList1_item {
    padding: 10px;
}

.demo-pagination-block {
    display: flex;
    justify-content: center;
}

.timeline-container {
    height: 700px;
    /* 设置固定高度，根据需要调整 */
    overflow-y: auto;
    /* 只在垂直方向上显示滚动条 */
    border: 1px solid #ddd;
    /* 可选: 为容器添加边框以便更清晰地看到容器的边界 */
    padding: 10px;
    /* 可选: 添加内边距以改善显示效果 */
}

.timeline-container1 {
    width: 100%;
    height: 100%;
    /* 设置固定高度，根据需要调整 */
    overflow-y: auto;
    /* 只在垂直方向上显示滚动条 */
    border: 1px solid #ddd;
    /* 可选: 为容器添加边框以便更清晰地看到容器的边界 */
    padding: 10px;
    /* 可选: 添加内边距以改善显示效果 */
}
</style>